<template>
  <div class="pager-container">
    <a @click="handleClick(1)" :class="{ disabled: currentPage === 1 }"
      >|&lt;&lt;</a
    >
    <a
      @click="handleClick(currentPage - 1)"
      :class="{ disabled: currentPage === 1 }"
      >&lt;&lt;</a
    >
    <a
      @click="handleClick(n)"
      :class="{ active: currentPage === n }"
      v-for="(n, i) in numbers"
      :key="i"
      >{{ n }}</a
    >
    <a
      @click="handleClick(currentPage + 1)"
      :class="{ disabled: currentPage === pageNumber }"
      >&gt;&gt;</a
    >
    <a
      @click="handleClick(pageNumber)"
      :class="{ disabled: currentPage === pageNumber }"
      >&gt;&gt;|</a
    >
  </div>
</template>

<script>
export default {
  props: {
    currentPage: {
      type: Number,
      default: 1,
    },
    total: {
      type: Number,
      default: 0,
    },
    limit: {
      type: Number,
      default: 10,
    },
    visibleNumber: {
      type: Number,
      default: 3,
    },
  },
  computed: {
    //最大页码
    pageNumber() {
      return Math.ceil(this.total / this.limit);
    },
    //可视的最小页码数
    visibleMinNumber() {
      let n = this.currentPage - Math.floor(this.visibleNumber / 2);
      return n <= 0
        ? 1
        : this.currentPage === this.pageNumber
        ? this.pageNumber - (this.visibleNumber - 1)
        : n;
    },
    //可视的最大页码数
    visibleMaxNumber() {
      let n = this.visibleMinNumber + this.visibleNumber - 1;
      return n <= this.pageNumber ? n : this.pageNumber;
    },
    //遍历显示的页码
    numbers() {
      let arr = [];
      for (
        let index = this.visibleMinNumber;
        index <= this.visibleMaxNumber;
        index++
      ) {
        arr.push(index);
      }
      return arr;
    },
  },
  methods: {
    handleClick(newPage) {
      if (
        newPage <= 0 ||
        newPage > this.pageNumber ||
        newPage === this.currentPage
      )
        return;
      this.$emit("pageChanged", newPage);
    },
  },
};
</script>

<style lang="less" scoped>
@import "~@/styles/var.less";
.pager-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  a {
    color: @primary;
    margin: 0 6px;
    cursor: pointer;
    &.disabled {
      color: @lightWords;
      cursor: not-allowed;
    }
    &.active {
      color: @words;
      font-weight: bold;
      cursor: text;
    }
  }
}
</style>
